#pragma once
#include <afxmt.h>
class CErrorMag
{

	CStdioFile m_f;

public:
	CString GetExePath()
	{
#pragma warning(disable : 4996)
		CString sPath = _T("");

		if(sPath.IsEmpty())
		{
			TCHAR szPath[MAX_PATH];
			GetModuleFileName(NULL, szPath,MAX_PATH);

			TCHAR szDrive[MAX_PATH];
			TCHAR szDir[MAX_PATH];
			_tsplitpath(szPath,szDrive,szDir,0,0);
			_stprintf(szPath,_T("%s%s"),szDrive,szDir);

			sPath = szPath;
		}
		if(sPath.Right(1).CompareNoCase(_T("\\")) != 0)
			sPath.Append(_T("\\"));

		return sPath;
	}
	bool Open()
	{
		if(m_f.m_hFile == NULL || m_f.m_hFile == CFile::hFileNull)
		{
			CString sPath = GetExePath()+ "Log.txt";
			CFileException er;
			if(!m_f.Open(sPath,CFile::modeCreate|CFile::modeReadWrite,&er))
				return false;
		}

		if(m_f.m_hFile == NULL || m_f.m_hFile == CFile::hFileNull)
			return false;

		return true;
	}

	void WriteError(CString sMsg)
	{
		if(!Open())
			return ;

		CCriticalSection sec;
		sec.Lock();
		m_f.SeekToEnd();
		m_f.WriteString("\r\n");
		m_f.WriteString(sMsg);
		sec.Unlock();

	}

	void WriteErrorFormat(CString pszFormat,...)
	{
		CString sMsg;
		va_list argList;
		va_start( argList, pszFormat );
		sMsg.FormatV( pszFormat, argList );
		va_end( argList );

		WriteError(sMsg);
	}
};
static CErrorMag g_ErrMag;

inline int SendMsg(SOCKET nSocket,CString sMsg)
{
	//OnCode(sMsg);
	int icount = sMsg.GetLength();
	int iRet = send(nSocket,sMsg.GetBuffer(),icount+1,0);

	return iRet;
}

inline int RecvMsg(SOCKET nSocket,CString& sMsg)
{
	char recvBuf[1024];
	memset(recvBuf,0,sizeof(recvBuf));
	int iRet = recv(nSocket,recvBuf,1024,0);
	sMsg = recvBuf;
	//OnUncode(sMsg);
	return iRet;
}

template< typename T >
inline long GetVectorCount(std::vector< T  > & vtStruct)
{
	long nCount = 0;
	std::vector<T > ::iterator beg = vtStruct.begin();
	for ( ; beg != vtStruct.end() ; ++ beg)
	{
		T  ptypOne = *beg;
		if(ptypOne)
		{
			nCount++;
		}
	}

	return nCount;
}


template< typename T >
inline T GetVectorValue(long nItem ,std::vector< T  > & vtStruct)
{
	std::vector< T >::iterator beg = vtStruct.begin();
	long nCount = 0;
	for (; beg != vtStruct.end(); ++ beg)
	{
		T  ptypOne = *beg;
		if(ptypOne)
		{
			return ptypOne;
			nCount ++;
		}
	}

	return 0;
}



template< typename T >
inline bool FindVectorValue(std::vector< T  > & vtStruct,T value)
{
	std::vector< T >::iterator beg = vtStruct.begin();
	long nCount = 0;
	for (; beg != vtStruct.end(); ++ beg)
	{
		T  ptypOne = *beg;
		if(ptypOne == value)
		{
			return true;
		}
	}

	return false;
}
